import {DecoratorMetadata} from './meta/DecoratorMetadata';
import {ReflectUtils} from '../reflect/ReflectUtils';
import {ObjectType} from '../type';
import {createPropertyDecorator} from './util';


export interface AutowiredMetadata extends DecoratorMetadata {
  /** 属性名称 */
  propertyName: string;
  /**
   * 依赖Bean名称
   */
  beanName?: string;
  /**
   * 依赖Bean类型
   */
  beanType: ObjectType<any>;
  /**
   * 依赖的Bean是否必须存在
   */
  required: boolean;
}

export function Autowired(opts?: {
  /**
   * Bean名称，可选，为空使用类型注入
   */
  name?: string,
  /**
   * 是否必须，默认true，若为true且找不到对应的实例抛出异常
   */
  required?: boolean
}): PropertyDecorator;


export function Autowired(opts?): PropertyDecorator {
  let beanName, required;
  if (opts) {
    beanName = opts.name;
    required = opts.required;
  } else {
    required = true;
  }

  return createPropertyDecorator((target, meta) => {
    const autowiredMeta: AutowiredMetadata = {
      decorator: Autowired,
      propertyName: meta.name,
      beanName,
      required,
      beanType: meta.type,
    };

    ReflectUtils.addMetadata('summer:class:dependency', autowiredMeta, target);
    return autowiredMeta;
  });
}
